package com.link.speechdemo;

import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.VoiceWakeuper;
import com.iflytek.cloud.WakeuperListener;
import com.iflytek.cloud.WakeuperResult;
import com.iflytek.cloud.util.ResourceUtil;
import com.link.speechdemo.speech.UnderstanderSpeech;
import com.link.speechdemo.utils.MusicUtil;
import com.link.speechdemo.widget.RippleBackground;
import com.mob.tools.utils.Hashon;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements UnderstanderSpeech.iMyActivity {
    private String listen = "listen";
    private String talk = "talk";
    private ComponentName componentName;
    private DevicePolicyManager policyManager;
    // 声明键盘管理器
    KeyguardManager mKeyguardManager = null;
    //声明键盘锁
    private KeyguardManager.KeyguardLock mKeyguardLock = null;
    //声明电源管理器
    private PowerManager pm;
    private PowerManager.WakeLock wakeLock;
    // 唤醒结果内容
    private String resultString;

    // 设置门限值 ： 门限值越低越容易被唤醒
    private final static int MAX = 60;
    private final static int MIN = -20;
    private int curThresh = 10;
    private String threshStr = "门限值：";
    private String keep_alive = "1";
    private String ivwNetMode = "0";
    private VoiceWakeuper mIvw = null;

    private Button btnSleepScreen;
    private Button btnUnScreen;
    private Button btnTest;
    private Timer mTimer;
    public static MainActivity instance;
    private RippleBackground rippleBackground;
    private ImageView ivPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSleepScreen = (Button) findViewById(R.id.btnSleepScreen);
        btnUnScreen = (Button) findViewById(R.id.btnUnScreen);
        btnUnScreen.setOnClickListener(new MyListener());
        btnTest = (Button) findViewById(R.id.btnTest);
        btnTest.setOnClickListener(new MyTestListener());
        rippleBackground = (RippleBackground) findViewById(R.id.content);
        ivPhone = (ImageView) findViewById(R.id.iv_phone);
        instance = this;
        init();
        Singleton.getUInstance().setCallBack(this);
        ivPhone.setOnClickListener(new MyOnClickListener());
    }

    public void init() {
        setParam();
        //4.开始唤醒
        mIvw.startListening(new MyWakeuperListener());
    }

    public void onClick(View view) {
        policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        boolean isAdminActive = policyManager.isAdminActive(componentName);
        if (isAdminActive) {
            mTimer = new Timer();
            mTimer.schedule(new MyTimerTask(), 200);
        } else {
            activeManage();
            mTimer = new Timer();
            mTimer.schedule(new MyTimerTask(), 200);
        }
        Log.i("onClick", "执行了");
    }

    public void LockScreen() {
        policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        boolean isAdminActive = policyManager.isAdminActive(componentName);
        if (isAdminActive) {
            mTimer = new Timer();
            mTimer.schedule(new MyTimerTask(), 200);
        } else {
            activeManage();
            mTimer = new Timer();
            mTimer.schedule(new MyTimerTask(), 200);
        }
        Log.i("onClick", "执行了");
    }

    @Override
    public void callBack() {
        init();
    }

    class MyWakeuperListener implements WakeuperListener {

        @Override
        public void onBeginOfSpeech() {

        }

        @Override
        public void onResult(WakeuperResult wakeuperResult) {
            //唤醒结果回调接口(返回Json格式结果，开发者可参见 附件13.4)
            try {
                String result = wakeuperResult.getResultString();
                Log.e("WakeuperResult-onResult", result.toString());
                int id = getResolveJson(result);
                Log.d("id", id + "");
                switch (id) {
                    case 0:
                        LockScreen();
                        break;
                    case 1:
                        WakeScreen();
                        mIvw.stopListening();
                        Singleton.getSInstance().init("主人，你好。需要什么帮助吗？");
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onError(SpeechError speechError) {
            Log.e("WakeuperResult-onError", speechError.toString());
        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }

        @Override
        public void onVolumeChanged(int i) {

        }
    }

    /**
     * 唤醒屏幕
     */
    public void WakeScreen() {
        //获取电源的服务
        pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //获取系统服务
        mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        //点亮亮屏
        wakeLock = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
        wakeLock.acquire();
        Log.i("Log : ", "------>mKeyguardLock");
        //初始化键盘锁，可以锁定或解开键盘锁
        mKeyguardLock = mKeyguardManager.newKeyguardLock("");
        //禁用显示键盘锁定
        mKeyguardLock.disableKeyguard();
    }

    /**
     * 屏幕休眠
     */
    public void SleepScreen() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "TAG");
        wakeLock.acquire();
        //做我们的工作，在这个阶段，我们的屏幕会持续点亮
        Log.e("SleepScreen", "我睡觉了，再见。");
        //初始化键盘锁，可以锁定或解开键盘锁
        //获取系统服务
        mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        mKeyguardLock = mKeyguardManager.newKeyguardLock("");
        //禁用显示键盘锁定
        mKeyguardLock.disableKeyguard();
        //释放锁，屏幕熄灭。
        wakeLock.release();

    }

//    /**
//     * 锁屏
//     */
//    public void LockScreen() {
//        policyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
//        policyManager.lockNow();//锁屏
//    }

    /**
     * 申请用户权限
     */
    private void activeManage() {
        //AdminReceiver 继承自 DeviceAdminReceiver
        componentName = new ComponentName(this, LockReceiver.class);
        // 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);

        //权限列表
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);

        //描述(additional explanation)
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "------ 屏幕锁定 ------");
        startActivity(intent);
    }

    /**
     * 解析服务器返回的唤醒词
     *
     * @param result
     */
    private int getResolveJson(String result) {
//        result = result.replace("var returnCitySN = {", "{").replace("};", "}");
        int id = (int) (new Hashon().fromJson(result).get("id"));
        Log.d("id", id + "");
        return id;
    }

    class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            policyManager.lockNow();
            mTimer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        if (wakeLock != null)
            wakeLock.release();
        super.onDestroy();
    }

    class MyListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Singleton.getUInstance().init();
        }
    }

    /**
     * 设置参数
     */
    private void setParam() {
        //1.创建唤醒对象
        mIvw = VoiceWakeuper.createWakeuper(this.getApplicationContext(), null);
        //2.获取唤醒词路径，resPath为唤醒资源路径
        String resPath = ResourceUtil.generateResourcePath(this, ResourceUtil.RESOURCE_TYPE.assets, "ivw/" + getString(R.string.app_id) + ".jet");
        //3.设置唤醒参数，详见《iFlytek MSC Reference Manual》SpeechConstant类
        // 设置唤醒词加载路径
        mIvw.setParameter(SpeechConstant.IVW_RES_PATH, resPath);
        //唤醒门限值，根据资源携带的唤醒词个数按照“id:门限;id:门限”的格式传入
        mIvw.setParameter(SpeechConstant.IVW_THRESHOLD, "0:" + 5);
        //设置当前业务类型为唤醒
        mIvw.setParameter(SpeechConstant.IVW_SST, "wakeup");
        //设置唤醒一直保持，直到调用stopListening，传入0则完成一次唤醒后，会话立即结束（默认0）
        mIvw.setParameter(SpeechConstant.KEEP_ALIVE, "1");
        mIvw.setParameter(SpeechConstant.IVW_NET_MODE, "2");
    }

    class MyTestListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            MusicUtil.getMusic(getApplicationContext());
        }
    }

    boolean type = false;
    class MyOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (type) {
                rippleBackground.stopRippleAnimation();
                rippleBackground.startRippleAnimation(talk);
                type = false;
            } else {
                rippleBackground.stopRippleAnimation();
                rippleBackground.startRippleAnimation(listen);
                type = true;
            }
        }
    }


}
